var playerData = require('../scripts/network/playerData');
var a = new Array;
var player1pai = new Array;
var player2pai = new Array;
var player3pai = new Array;
var dizhupaiKey;
var dizhupai = new Array;
var pukepai ;
var playerCard = new Array;

var SITDOWN = 2;
var STANDUP = 1;

var ppp = new Array;
cc.Class({
    extends: cc.Component,

    properties: {
    //    textButton: cc.Button,
    //    text2Button: cc.Button,

       _touchBegan: null,
       _touchMoved: null,
    },

   

     onLoad () {
        this.onTouchEvent();
        //this.initArray();

        // this.textButton.node.on('click',this.text,this);
        // this.text2Button.node.on('click',this.text2,this);
        
        //console.log('打乱数组');
        //this.shuffle(a);
         
        
         //console.log('数组长度:'+ a.length);

         //console.log("发牌");
         //this.fapai(a);

         //console.log("对牌的大小排序")
         //在对牌的大小的排序的时候，牌的花色也是有序的  （从大到小排序）
         //this.paixu(player1pai,2);
       
  
     },

     update() {
        ppp = playerData.gamePlayer.initPai;
     },

     start () {
     },
     
     //对相应的牌实例化
     text: function (arr) {
        for(var i = 0; i< arr.length; i++) {
            var wizhi = arr[i][0];
            var j =i;
            this.fapai3(wizhi,j);
         }
         return i;
         //console.log(ppp.length);
        
     },


    //  init: function () {
    //      this.initArray();
    //      this.shuffle(a);
    //      this.fapai(a);
    //  },

     //显示和设置实例化后的牌
     text2: function (arr) {
        var draw = 960 / 2 - ((arr.length -1) /2) * 30;
        for(var i=0; i<arr.length; i++) {
            cc.find("Canvas/pukepaiEar").addChild(arr[i]);
            arr[i].position = cc.v2(draw + i*30,75);
            /**
             * 等同于前面
             * cc.director.getScene().addChild(ppp[i]);
             * ppp[i].parent = cc.find("Canvas/pukepaiEar");
             * ppp[i].y = 80;
             * ppp[i].x = 250 + i *30;
             */
            //var number1 = player1pai[i][2];
            //this.sendNumber(ppp[i],number1);   //这也是一个异步加载问题
        }
     },

     

     /**
      * 对异步加载问题的处理方法 ， 使用方法去调用。给牌加Button组件，使用这个方式可以点击牌的时候得到相应数字
      * 但是不应该给牌添加Button 组件，因为cc.Node.EnenType 在点击有Button组件的Node时没反应
      * @param {牌数组} ppp 
      * @param {牌的数字} number 
      */
      sendNumber: function (ppp,number) {
        //ppp.getComponent(cc.Button).node.on('click',function () {console.log(number);},this);
     },

     //这边需要逆序输出, 因为我们的牌时从左往右递增，所以要先从左边开始判断是否点中牌。顺序会造成遮挡问题
     _getCardForTouch: function (touch, cardArr) {
        for(var k = cardArr.length -1; k >= 0; k--) {
            var box = cardArr[k].getBoundingBox();//返回父节坐标系下的轴向对齐的包围盒
            //判断box中是否包含指定坐标点touch
            if( box.contains(touch) ) {
                //根据isChiose来判断是否被点击，被点击就设为true。在牌的实例化中定义的isChiose
                cardArr[k].isChiose = true;
                //cardArr[k].opacity = 155;
                //点击后该牌的颜色
                cardArr[k].color = new cc.color(219,219,219); 
                return cardArr[k];
            }else {
            }
        }
     },

     /**
      * 用开始点和移动点画出一个矩形，当滑动多选的牌有离开这个矩形时，设置为初始状态
      * 无论向左还是向右，这个矩形都是以左边为基点，向右扩展
      * @param {开始触摸点} touchBegan 
      * @param {移动触摸点} touchMoved 
      */
     _checkSelectCardReserve(touchBegan, touchMoved) {
        ppp = playerData.gamePlayer.initPai;
        var p1 = touchBegan.x < touchMoved.x ? touchBegan : touchMoved;
        var width = Math.abs(touchBegan.x - touchMoved.x);
        var height = Math.abs(touchBegan.y - touchMoved.y);
        var rect = cc.rect(p1.x, p1.y, width, height);
        //从左向右滑动，在往回
        for (var i in ppp) {
            if (!ppp[i].getBoundingBox().intersects(rect)) {
                ppp[i].isChiose = false;
                ppp[i].color = new cc.color(255, 255, 255);
            }
        }
        //从右向左，再往回
        if (p1 == touchMoved) {
            for (var i in ppp) {
                if((p1.x - ppp[i].x) > -25) { //这个的数值理论上因该是牌长度的一半，但实际上。。。说不清楚
                    ppp[i].color = new cc.color(255, 255, 255);
                    ppp[i].isChiose = false;
                }
            }
        }
     },

     touchBegan: function (event) {
        //ppp = playerData.gamePlayer.initPai;
        var touches = event.getTouches();//获取触摸点的列表  返回的是一个数组
        var touchLoc = touches[0].getLocation();
        //将一个点转换到节点坐标系，并加上锚点的坐标。
        //也就是说返回的坐标是相对于节点包围盒坐下角的坐标。
        this._touchBegan = cc.find("Canvas/pukepaiEar").convertToNodeSpace(touchLoc);
        this._getCardForTouch(touchLoc, ppp);
     },

     /**
      * isChiose 是用来判断是否被点击，无论处于什么状态，是要被点击都会被设置为 ture , 再本方法里再重新设置为false
      * 通过 SITDOWN 和 STADNUP 来判断 牌 的状态， 初始状态为 SITDOWN
      * @param {*} event 
      */
     touchEnd: function (event) {
        var touches = event.getTouches();
        var touchLoc = touches[0].getLocation();
        //ppp = playerData.gamePlayer.initPai;
        for (var k in ppp) {
            //ppp[k].opacity = 255;
            //牌是被选中的
            if (ppp[k].isChiose == true) {
                ppp[k].color = new cc.color(255,255,255);
                ppp[k].isChiose =false;
                if(ppp[k].status == SITDOWN) {
                    ppp[k].status = STANDUP;
                    ppp[k].y += 20;
                    playerCard[k][5] = 1;
                    //通过事件名发送自定义事件，点中的牌
                    cc.find('Canvas').emit('sendPukepaiMessage',playerCard[k]);
                }else {
                    ppp[k].color = new cc.color(255,255,255);
                    ppp[k].status = SITDOWN;
                    ppp[k].y -= 20;
                    playerCard[k][5] = 0;
                    //放下的牌
                    cc.find('Canvas').emit('sendSitdownMessage',playerCard[k]);
                
                }
            }
        }
     },

     setPlayerCard: function (arr) {
        playerCard = arr;  //玩家牌的 二维数组信息
     },

     touchMoved: function (event) {
        //ppp = playerData.gamePlayer.initPai;
         var self = this;
        var touches = event.getTouches();
        var touchLoc = touches[0].getLocation();
        this._touchMoved = cc.find("Canvas/pukepaiEar").convertToNodeSpace(touchLoc);
        self._getCardForTouch(touchLoc,ppp);
        this._checkSelectCardReserve(this._touchBegan, this._touchMoved);
     },

     onTouchEvent: function () {
        var self = cc.find("Canvas/pukepaiEar");
        cc.find("Canvas/pukepaiEar").on(cc.Node.EventType.TOUCH_START, this.touchBegan, this);
        //cc.find("Canvas/pukepaiEar").on(cc.Node.EventType.TOUCH_CANCEL, this.touchCancel, this);
        cc.find("Canvas/pukepaiEar").on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
        cc.find("Canvas/pukepaiEar").on(cc.Node.EventType.TOUCH_MOVE, this.touchMoved, this);
     },

     offTouchEvent: function () {
        cc.find("Canvas/pukepaiEar").off(cc.Node.EventType.TOUCH_START, this.touchBegan, this);
        //cc.find("Canvas/pukepaiEar").off(cc.Node.EventType.TOUCH_CANCEL, this.touchCancel, this);
        cc.find("Canvas/pukepaiEar").off(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
        cc.find("Canvas/pukepaiEar").off(cc.Node.EventType.TOUCH_MOVE, this.touchMoved, this);
     },
     
    

   
     //设置延时
     sleep: function (ms) {

        for(var t = Date.now();Date.now() - t <= ms;);
   
    },

    /**
     * a[i][0] 是拍的在数组的位置，初始顺序是 A~k 1~13, 按颜色顺序 黑红梅方 依次排列
     * a[i][1] 是颜色 4是黑桃 ， 3：红桃 2：梅花 1：方块
     * a[i][2] 是代表的数字大小  其中A:14  2:15 小王：16 大王：17
     */
    initArray: function () {
        for(var i = 0; i < 54; i++ ) {
            a[i] = new Array(i);     //定义二维数组
            if(i < 13) {
               a[i][0] = i +1;
               a[i][1] = 4;
               if(i < 2) {
                   a[i][2] = 14 + i;
               }else {
                   a[i][2] = i + 1;
               }
            }else if (i < 26) {
                a[i][0] = i +1;
                a[i][1] = 3;
                if(i < 15) {
                    a[i][2] = 14 + i - 13;
                }else {
                    a[i][2] = i + 1 - 13;
                }
            }else if (i < 39) {
                a[i][0] = i+1;
                a[i][1] = 2;
                if (i < 28) {
                    a[i][2] = 14 + i - 26;
                }else {
                   a[i][2] = i + 1 - 26;
                }
            }else if (i < 52) {
                a[i][0] = i +1;
                a[i][1] = 1;
                if(i < 41) {
                    a[i][2] = 14 + i - 39;
                }else {
                    a[i][2] = i +1 -39;
                }
            }else if (i == 52) {
                a[i][0] = i +1;
                a[i][1] = 5;
                a[i][2] = 16;
            }else if (i==53) {
                a[i][0] = i +1;
                a[i][1] = 6;
                a[i][2] = 17;
            }
        }
        playerData.gamePlayer.paiArray = a;
        console.log('组初始化');
        for (var i =0; i< 54 ; i++){
            console.log(a[i]);
        }
        console.log('-----------');
    },

    /**
     *  打乱数组，随即洗牌
     * @param {arr} arr 
     */
    shuffle: function (arr) {
        var i = arr.length ,t ,j;
        while (i) {
            j = Math.floor(Math.random() * i--);
            t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
        console.log('打乱数组');
        for (var i =0; i< 54 ; i++){
            console.log(a[i]);
        }

    },

    /**
     * 插入排序
     * @param {需要排序的数组} arr 
     * @param {二维尾标} n 
     */
    paixu: function (arr, n) {
        for(var i = 1; i < arr.length; i++){
            var next = arr[i][n];
            var key = arr[i];
            var j = i -1; 
            while( j >= 0 && (next > arr[j][n])){
                arr[j+1] = arr[j];
                j--;
            }
           arr[j +1] = key;
        }    
        for (var i =0; i< arr.length ; i++){
            console.log(arr[i]);
        }
        console.log('-----------');
    },

    /**
     * 随即发牌，选取地主牌，规定最后三张为 留给地主的牌
     * @param {*} arr 
     */
    fapai: function (arr) {
        dizhupaiKey = Math.random(arr);
        for(var i= 0, k = 0; i< arr.length - 3; k++) {
            player1pai[k] = arr[i];
            player2pai[k] = arr[i+1];
            player3pai[k] = arr[i+2];
        
            i = i +3;
        }

        for(var i = 51,k = 0; i< arr.length; i++,k++) {
            dizhupai[k] = arr[i];
        }
        playerData.gamePlayer.player1pai = player1pai;
        //cc.find('Canvas').emit('player1pai', player1pai);
        cc.find('Canvas').emit('player2pai', player2pai);
        cc.find('Canvas').emit('player3pai', player3pai);
        cc.find('Canvas').emit('dizhupaiKey', dizhupaiKey);
        cc.find('Canvas').emit('dizhupai', dizhupai);
        console.log("玩家1的牌：" + player1pai.length);
        for(var i =0; i< player1pai.length; i++){
            console.log(player1pai[i]);
        }
    
    },

    /**
     * 牌的实例化， cc.load 为异步加载，在实例化的时候用一个数组来存储已经实例化的牌
     * @param {牌prefab的名字的尾号} weizhi 
     * @param {代表第几张牌} i 
     */
    fapai3: function (weizhi, i) {
        cc.loader.loadRes("prefab/pukepai_"+weizhi, cc.Prefab, function(err,prefab){
            if(err){
                cc.error(err.message);
                return;
            }
            pukepai = cc.instantiate(prefab);
            pukepai.status = SITDOWN;
            pukepai.isChiose = false;
            pukepai.index = i;
            //存储实例化的牌
            //ppp[i] 和 player1pai[i] 是同步的
            playerData.gamePlayer.initPai[i] = pukepai;
            
        });
    }

    // update (dt) {},
});



